﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using System.ServiceModel.DomainServices.Server.ApplicationServices;
using System.Security.Principal;
using System.Web.Security;
using System.Web;

namespace DYSales.Web
{
    [EnableClientAccess]
    //[EnableClientAccess(RequiresSecureEndpoint = true)]
    public class AuthenDomainService : AuthenticationBase<User>
    {
        EntityContext ect;

        // To enable Forms/Windows Authentication for the Web Application, 
        // edit the appropriate section of web.config file.
        protected override bool ValidateUser(string userName, string password)
        {
            //var rdr = conSQL.ExcuteSqlReader("SELECT * FROM Operators WHERE ot_用户名 = '" + userName + "'");
            //var user = new Operator();
            //while (rdr.Read())
            //{
            //    user.ot_用户名 = rdr.GetString(1);
            //    user.ot_密码 = rdr.GetString(2);
            //    user.ot_权限组 = rdr.GetString(3);
            //    if (user.ot_密码.Equals(password))
            //    {
            //        FormsAuthentication.SetAuthCookie(user.ot_用户名, true);
            //        SetCookies();
            //        return true;
            //    }
            //}
            //rdr.Dispose();
            //return false;

            if (ect == null)
            {
                ect = new EntityContext();
            }
            var user = ect.Operators.FirstOrDefault(o => o.ot_用户名.Equals(userName));
            if (user != null)
            {
                if (user.ot_密码.Equals(password) && user.ot_启用)
                {
                    FormsAuthentication.SetAuthCookie(user.ot_用户名, true);
                    SetCookies();
                    return true;
                }
            }
            return false;
        }

        void SetCookies()
        {
            HttpCookie lcookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
            lcookie.Expires = DateTime.Now.AddDays(2);
        }

        // 获取当前已验证的用户信息
        protected override User GetAuthenticatedUser(IPrincipal pricipal)
        {
            User user = new User();
            user.Name = pricipal.Identity.Name;
            var u = ect.Operators.FirstOrDefault(o => o.ot_用户名.Equals(pricipal.Identity.Name));
            if (u != null)
            {
                user.Roles = new string[] { u.ot_权限组 };
            }
            return user;
        }
    }


}